package com.gxa.saas.controller;

import com.gxa.saas.pojo.GoodsXq;
import com.gxa.saas.pojo.Storage;
import com.gxa.saas.pojo.StoreHouseIn;
import com.gxa.saas.service.StoreHouseInService;
import com.gxa.saas.utils.JsonResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/storehouseIn")
@ResponseBody
public class StoreHouseInController {
    Map map=new HashMap();

    @Autowired
    StoreHouseInService storeHouseInService;

    @ApiOperation("查询入库表信息")
    @PostMapping(value = "/selectInStore")
    public Map selectInStore(Integer limit,Integer size){
        List<StoreHouseIn> storeHouseIns = storeHouseInService.selectByPage(limit, size);
        Integer totalCountIn = storeHouseInService.getTotalCountIn();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(storeHouseIns);
        jsonResult.set("total",totalCountIn);
        return jsonResult.getMap();
    }


    @ApiOperation("审批入库单")
    @PostMapping("/checkIn")
    public Map checkIn(Integer id,
                       @RequestParam(value = "comments",required = false) String comments) {

        storeHouseInService.updateCheck(id,comments);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }


    @ApiOperation("入库单按照ID删除")
    @PostMapping("/deleteById")
    public Map deleteByIdIn(Integer id){
        storeHouseInService.deleteById(id);
        return null;
    }

    @ApiOperation("入库单多条件查询")
    @PostMapping("/selectByDateIn")
    public Map selectByDateAndDepotAndStateIn(
            @RequestParam(value = "from",required = false)String from,
            @RequestParam(value = "to",required = false)String to,
            @RequestParam(value = "vendor",required = false)String vendor,
            @RequestParam(value = "depot",required = false)String depot,
            @RequestParam(value = "state",required = false)String state,
            Integer page,Integer size
    ){
        Map map=new HashMap();
        map.put("from",from);
        map.put("to",to);
        map.put("vendor",vendor);
        map.put("depot",depot);
        map.put("state",state);
        map.put("page",(page-1)*size);
        map.put("size",size);
        System.out.println(map);
        JsonResult jsonResult=new JsonResult();
        List<StoreHouseIn> storeHouseIns = storeHouseInService.selectByDateAndVendorAndDepotAndState(map);
        Integer total = storeHouseInService.getTotalByTiaojian(map);
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(storeHouseIns);
        jsonResult.set("total",total);
        return jsonResult.getMap();
    }

    @ApiOperation("入库单查询库存表")
    @PostMapping (value = "/inStoragelist")
    public Map selectStorageListIn(Integer limit,Integer size){
        List<Storage> storageList = storeHouseInService.getStorageList(limit, size);
        Integer totalStorageIn = storeHouseInService.getTotalStorageIn();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(storageList);
        jsonResult.set("total",totalStorageIn);
        return jsonResult.getMap();

    }

    @ApiOperation("入库的下拉列表")
    @PostMapping (value = "/inDropDownlist")
    public Map getDropDownListIn(){
        List<StoreHouseIn> dropDownList = storeHouseInService.getDropDownList();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(dropDownList);
        return jsonResult.getMap();
    }

    @ApiOperation("入库的商品模糊查询")
    @PostMapping (value = "/outLike")
    public Map getGoodLike(String goodsName,Integer page,Integer size){
        List<Storage> goodsLikeList = storeHouseInService.selectStoreDetail(goodsName, page, size);
        Integer totalByLike = storeHouseInService.getTotalByLike(goodsName);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(goodsLikeList);
        jsonResult.set("total",totalByLike);
        return jsonResult.getMap();
    }


    @ApiOperation(value = "入库预览--商品明细查询 进一个接口",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "",dataType = "int",paramType = "query"),
    })
    @PostMapping("/selectByGoodsXq")
    public Map selectByGoodsXqList(Integer orderId){
        StoreHouseIn storeHouseIn = storeHouseInService.selectById(orderId);
        List<GoodsXq> goodsXqs = storeHouseInService.selectDetailById(orderId);
        Integer count=goodsXqs.size();
        Double sumPrice=0.00;
        for (int i = 0; i <goodsXqs.size() ; i++) {
            Double money = goodsXqs.get(i).getMoney();
            sumPrice=sumPrice+money;
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCount("200");
        jsonResult.setCount("查询成功");
        jsonResult.setData(goodsXqs);
        jsonResult.set("count",count);
        jsonResult.set("sumPrice",sumPrice);
        jsonResult.set("storeHouseIn",storeHouseIn);
        return jsonResult.getMap();
    }


    @ApiOperation(value = "编辑提交订单",produces = "query")
    @ApiImplicitParams({
    })
    @PostMapping("/addInList")
    public Map insert(@RequestParam(value = "vendor",required = true)String vendor,
                      @RequestParam(value = "depot",required = true)String depot,
                      @RequestParam(value = "amount",required = true)String amount,
                      @RequestParam(value = "id",required = true)Integer id
    ){
        Map map=new HashMap();
        map.put("vendor",vendor);
        map.put("depot",depot);
        map.put("amount",amount);
        map.put("id",id);
        Integer integer = storeHouseInService.update(map);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCount("200");
        jsonResult.setCount("添加成功");
        return jsonResult.getMap();
    }


    @ApiOperation(value = "搜索结果添加接口",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "搜索结果添加对应的商品id",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "outId",value = "对应订单编号id",dataType = "int",paramType = "query"),
    })
    @PostMapping("/addGoods")
    public Map insertGoods(Integer outId, Integer id){
        System.out.println("有请求进来了");
        Storage storage = storeHouseInService.selectByDetailId(id);
        StringBuilder big=new StringBuilder();
        StringBuilder small=new StringBuilder();
        GoodsXq goodsXq = new GoodsXq();

        String bigUnit=storage.getBigUnit();
        String bigPrice= String.valueOf(storage.getBigPrice());

        big.append(bigPrice);
        big.append("/");
        big.append(bigUnit);
        String smallUnit=storage.getSmallUnit();
        String smallPrice= String.valueOf(storage.getSmallPrice());
        small.append(smallPrice);
        small.append("/");
        small.append(smallUnit);
        goodsXq.setOrderId(outId);
        goodsXq.setName(storage.getName());
        goodsXq.setBigUnit(big.toString());
        goodsXq.setSmallUnit(small.toString());
        Double bigPrice1 = storage.getBigPrice();
        Double smallPrice1 = storage.getSmallPrice();
        goodsXq.setBigCount(1);
        goodsXq.setSmallCount(1);
        goodsXq.setGoodsType("正常");

        goodsXq.setMoney(bigPrice1*1+smallPrice1*1);
        goodsXq.setProtectedDate(new Date());
        Integer insert = storeHouseInService.insertGoodsXq(goodsXq);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCount("200");
        jsonResult.setCount("添加成功");
        return jsonResult.getMap();
    }


    @ApiOperation(value = "移除操作",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "删除的id",paramType = "query"),
    })
    @PostMapping("/deleteStore")
    public Map delete(Integer id){
        storeHouseInService.deleteDetailById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCount("200");
        jsonResult.setCount("删除成功");
        return jsonResult.getMap();
    }


    @ApiOperation(value = "+/- 接口统一调用",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "修改的商品明细id,不是订单id",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "bigCount",value = "修改后的大单位数量",dataType = "double",paramType = "query"),
            @ApiImplicitParam(name = "smallCount",value = "修改后的小单位数量",dataType = "double",paramType = "query"),
    })
    @PostMapping("/updateByPrice")
    public Map updateByPrice(Integer bigCount,Integer smallCount,Integer id){
        GoodsXq goodsXq = storeHouseInService.selectByGoodsXqId(id);
        String bigPrice=goodsXq.getBigUnit();
        int i = bigPrice.indexOf("/");
        String smallPrice=goodsXq.getSmallUnit();
        int j = smallPrice.indexOf("/");

        Double big= Double.valueOf(bigPrice.substring(0,i));
        Double small=Double.valueOf(smallPrice.substring(0,j));


        Double money=big*bigCount+small*smallCount;
        storeHouseInService.updateByPrice(bigCount,smallCount,money,id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCount("200");
        jsonResult.setCount("修改成功");
        return jsonResult.getMap();
    }

    @ApiOperation("导出入库单")
    @GetMapping(value = "/inlist")
    public void exportExcelIN(HttpServletResponse response) throws IOException {
        List<StoreHouseIn> storeHouseIns = storeHouseInService.selectAll();
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("客户信息列表");
        String fileName = "客户信息列表.xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String [] headers = {"编号","创建日期","出库仓库","业务员",
                "总金额","出库时间","发起人","审批人",
                "状态","审批意见","库存数量","付款方式"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        // 添加数据行:表头信息占用了第一行，所以要从第二行开始添加
        int rowNum = 1;
        for (StoreHouseIn item : storeHouseIns) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(dateFormat.format(item.getCreateDate()));
            dataRow.createCell(2).setCellValue(item.getVendor());
            dataRow.createCell(3).setCellValue(item.getDepot());
            dataRow.createCell(4).setCellValue(item.getAmount());
            dataRow.createCell(5).setCellValue(dateFormat.format(item.getTime()));
            dataRow.createCell(6).setCellValue(item.getUName());
            dataRow.createCell(7).setCellValue(item.getAName());
            dataRow.createCell(8).setCellValue(item.getState());
            dataRow.createCell(9).setCellValue(item.getComments());
            dataRow.createCell(10).setCellValue(item.getMount());
            rowNum++;
        }
        //返回给前端下载
        //指定文档内容类型
        response.setContentType("application/octet-stream");
        //指定响应头
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
